package com.eva.dict.loaders;

import com.eva.dao.system.model.SystemDictData;
import com.eva.dict.dao.SystemDictMapper;
import com.eva.framework.cache.CacheProxy;
import com.eva.framework.common.constants.CacheKeys;
import com.eva.framework.common.constants.ResponseStatus;
import com.eva.framework.common.exception.BusinessException;
import com.eva.dict.vo.SystemDictWithDataVO;
import com.eva.framework.dict.model.DictCache;
import com.eva.framework.dict.model.DictDataCache;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Component
public class SystemDictCacheLoader {

    @Resource
    private SystemDictMapper systemDictMapper;

    @Resource
    private CacheProxy<String, Map<String, DictCache>> cacheProxy;

    /**
     * 加载到缓存
     */
    public void loadToCache () {
        log.debug("加载字典数据至缓存");
        if (cacheProxy.get(CacheKeys.DICTIONARIES) != null) {
            log.debug("数据已加载至缓存，跳过本次加载！");
            return;
        }
        List<SystemDictWithDataVO> dictWithDataList = systemDictMapper.selectListWithData();
        List<DictCache> dictList = new ArrayList<>();
        for (SystemDictWithDataVO dictWithDataVO : dictWithDataList) {
            DictCache dictCache = new DictCache();
            BeanUtils.copyProperties(dictWithDataVO, dictCache, "dataList");
            List<DictDataCache> dataList = new ArrayList<>();
            for (SystemDictData data : dictWithDataVO.getDataList()) {
                DictDataCache dictDataCache = new DictDataCache();
                BeanUtils.copyProperties(data, dictDataCache);
                dataList.add(dictDataCache);
            }
            dictCache.setDataList(dataList);
            dictList.add(dictCache);
        }
        Map<String, DictCache> dictMap = new HashMap<>();
        for (DictCache dictCache : dictList) {
            if (dictMap.containsKey(dictCache.getCode())) {
                throw new BusinessException(ResponseStatus.DATA_ERROR, "字典中存在重复的code，请检查字典数据！");
            }
            dictMap.put(dictCache.getCode(), dictCache);
        }
        cacheProxy.put(CacheKeys.DICTIONARIES, dictMap);
        log.debug("字典数据缓存完成");
    }
}
